package com.bc.plugin.doc.resolver.help;

import com.power.doc.constants.DocGlobalConstants;
import com.power.doc.utils.DocClassUtil;

import java.util.List;

public class ClassTypeUtil {

    private static final String[] COLLECTION_PRE_NAME = new String[]{
            "java.util.List",
            "java.util.LinkedList",
            "java.util.ArrayList",
            "java.util.Set",
            "java.util.TreeSet",
            "java.util.HashSet",
            "java.util.SortedSet",
            "java.util.Collection",
            "java.util.ArrayDeque",
            "java.util.PriorityQueue"
    };

    /**
     * validate java collection
     *
     * @param type java typeName
     * @return boolean
     */
    public static boolean isCollection(String type) {
        for (int i = 0; i < COLLECTION_PRE_NAME.length; i++) {
            String pre = COLLECTION_PRE_NAME[i];
            if (type.startsWith(pre)) {
                return true;
            }
        }
        return false;
    }

    private static final String[] MAP_PRE_NAME = new String[]{
            "java.util.Map",
            "java.util.SortedMap",
            "java.util.LinkedHashMap",
            "java.util.HashMap",
            "java.util.concurrent.ConcurrentHashMap",
            "java.util.concurrent.ConcurrentMap",
            "java.util.Properties",
            "java.util.Hashtable"

    };

    /**
     * Check if it is an map
     *
     * @param type java type
     * @return boolean
     */
    public static boolean isMap(String type) {
        for (String pre : MAP_PRE_NAME) {
            if (type.startsWith(pre)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isSimpleType(String typeName) {
        return DocClassUtil.isPrimitive(typeName) || DocGlobalConstants.JAVA_OBJECT_FULLY.equals(typeName);
    }

    public static String unwrapJavaUtilType(String className) {
        className = unwrapArray(className);
        while (ClassTypeUtil.isCollection(className) || ClassTypeUtil.isMap(className)) {
            List<String> genericTypes = JavaClassUtil.getGenericTypes(className);
            if (genericTypes == null || genericTypes.isEmpty()) {
                return DocGlobalConstants.JAVA_OBJECT_FULLY;
            }
            className = genericTypes.get(genericTypes.size() - 1);
            className = unwrapArray(className);
        }
        if (className.length() == 1) {
            return DocGlobalConstants.JAVA_OBJECT_FULLY;
        }
        return className;
    }

    public static String unwrapArray(String className) {
        while (className.endsWith("[]")) {
            className = className.substring(0, className.lastIndexOf("[]"));
        }
        return className;
    }

}
